01.Riverpod 介绍
Riverpod 是一个 Dart/Flutter 下的状态管理框架,使用声明式和响应式编程。
Hello World
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'main.g.dart';
// We create a "provider", which will store a value (here "Hello world").
// By using a provider, this allows us to mock/override the value exposed.
@riverpod
String helloWorld(HelloWorldRef ref) {
return 'Hello world';
}
void main() {
runApp(
// For widgets to be able to read providers, we need to wrap the entire
// application in a "ProviderScope" widget.
// This is where the state of our providers will be stored.
ProviderScope(
child: MyApp(),
),
);
}
// Extend ConsumerWidget instead of StatelessWidget, which is exposed by Riverpod
class MyApp extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final String value = ref.watch(helloWorldProvider);
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Example')),
body: Center(
child: Text(value),
),
),
);
}
}
安装
Riverpod 由一系列包组成,对于 Flutter 开发来说,需要:
flutter pub add flutter_riverpod
flutter pub add riverpod_annotation
flutter pub add dev:riverpod_generator
flutter pub add dev:build_runner
flutter pub add dev:custom_lint
flutter pub add dev:riverpod_lint
其中:
- riverpod_lint:该包提供了代码检查规则,帮助您编写更好的代码,并提供自定义重构选项。
VS Code 插件:Flutter Riverpod Snippets
代码生成器
Riverpod 依赖代码生成特性,通过下面命令开启 build_runner 的 watch 自动检测文件变动生成:
dart run build_runner watch
riverpod_lint 启用方法
需要在 pubspec.yaml
旁边添加一个 analysis_options.yaml
,并包含以下内容:
analyzer:
plugins:
- custom_lint
本文作者:Maeiee
本文链接:01.Riverpod 介绍
版权声明:如无特别声明,本文即为原创文章,版权归 Maeiee 所有,未经允许不得转载!
喜欢我文章的朋友请随缘打赏,鼓励我创作更多更好的作品!